<!--
 * @author  dumeng
题库管理
-->
<template>
  <div class="exam-question">
    <div class="btn-container-title">
      <span>题库管理</span>
      <span v-if="breadList.length > 0">,当前选择</span>
      <span v-if="breadList.length" class="btn-container-title-select">{{ breadList.join('>') }}</span>
    </div>
    <el-container class="page-info">
      <split-pane split="vertical" :min-percent="0" :default-percent="28">
        <template slot="paneL">
          <div class="page-left">
            <div class="search-tree-wrap">
              <el-input v-model.trim="treeName" style="width:75%" placeholder="分类名称搜索" class="search-input" clearable @clear="clearSearchTree" />
              <el-button class="filter-item tree-filter" type="primary" @click="handleFilterTree">搜索</el-button>
            </div>
            <el-tree
              ref="tree"
              v-loading="treeLoading"
              :data="treeData"
              :props="defaultProps"
              :expand-on-click-node="false"
              :default-expanded-keys="['-1']"
              class="dictTree"
              highlight-current
              node-key="id"
              :filter-node-method="filterNode"
              @node-click="handleTreeClick"
            >
              <span slot-scope="{ node }" class="custom-tree-node">
                <span>{{ node.label }}</span>
              </span>
            </el-tree>
          </div>
        </template>
        <template slot="paneR">
          <el-main class="page-right">
            <div v-if="!isShow" class="ts-con">
              <div class="ts">
                <i class="el-icon-info" />
                <span v-html="showMsg" />
              </div>
            </div>
            <div v-else>
              <el-collapse-transition>
                <div class="search merge">
                  <span class="svg-container">
                    <svg-icon icon-class="search" />
                  </span>
                  <el-input v-model.trim="search.content" placeholder="请输入题干进行搜索" class="search-input" @keyup.enter.native="handleFilter" />
                  <div class="search-btn">
                    <el-button class="filter-item" type="primary" @click="handleFilter">搜索</el-button>
                    <el-button class="filter-item" type="primary" @click="resettingBtn">重置</el-button>
                  </div>
                </div>
              </el-collapse-transition>
              <div class="btn-container-btns">
                <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate">新增</el-button>
                <!-- <el-button class="filter-item" style="margin-left: 10px;" @click="handleImport">导入</el-button> -->
                <el-button class="filter-item" style="margin-left: 10px;" @click="handleImportPass">导入闯关试题</el-button>
                <el-button class="filter-item" style="margin-left: 10px;" @click="handleDeletes">批量删除</el-button>
                <!--<el-button class="filter-item" type="primary" style="margin-left: 10px;" @click="$router.back()">返回</el-button>-->
              </div>
              <div class="table">
                <my-table
                  :list="list"
                  :filter-column="filtercolumn"
                  tag="questionManage"
                  :source-arr="['img']"
                  operationwidth="80"
                  :list-loading="listLoading"
                  @handleSelectionChange="handleSelectionChange"
                >
                  <el-table-column label="操作" fixed="right" align="center" min-width="80" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                      <el-button v-if="scope.row.type == 60" type="text" size="mini" @click="handleAddChild(scope.row)">增加试题</el-button>
                      <el-button type="text" size="mini" @click="handleUpdate(scope.row)">修改</el-button>
                      <el-button type="text" size="mini" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                  </el-table-column>
                </my-table>
              </div>
              <div class="btn-pagion fix">
                <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
              </div>
            </div>
          </el-main>
        </template>
      </split-pane>
    </el-container>
    <el-dialog v-el-drag-dialog :close-on-click-modal="false" :visible.sync="uploadQuesDialogVisible" title="上传试卷组成" center width="600px">
      <el-row :gutter="20" style="height: 300px;display: flex;align-items: center;justify-content: center;">
        <el-col :span="12">
          <div class="grid-content download">
            <div class="img-con">
              <img src="../images/ques-down.png">
            </div>
            <el-button type="primary" @click="handleDownload">下载模版</el-button>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="grid-content upload">
            <div class="img-con">
              <img src="../images/ques-upload.png">
            </div>
            <el-button type="primary" @click="handleUploadQues">上传excel</el-button>
          </div>
        </el-col>
      </el-row>
    </el-dialog>
    <el-dialog v-el-drag-dialog :close-on-click-modal="false" :visible.sync="dialogUploadVisible" title="上传文件" center width="500px">
      <el-upload
        ref="upload"
        v-loading="loadingUpload"
        element-loading-text="正在上传请稍后"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
        :auto-upload="false"
        :on-success="uploadSuccess"
        :on-error="uploadError"
        :action="uploadaction"
        :headers="uploadHeaders"
        :data="uploadData"
        accept=".xls, .xlsx"
        class="upload-demo"
        drag
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div slot="tip" class="el-upload__tip">
          只能上传.xls,.xlsx
          <span class="downFile" @click="handleDownload">下载模板</span>
        </div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button style="padding: 8px 30px;" type="primary" @click="dialogUploadVisible = false">取消</el-button>
        <el-button style="padding: 8px 30px;" type="primary" @click="submitUpload()">确认</el-button>
      </span>
    </el-dialog>
    <el-dialog v-el-drag-dialog :close-on-click-modal="false" :visible.sync="dialogUploadErrorTextVisible" title="错误信息" center width="500px">
      <div class="error-text" style="height: 600px;overflow-y: auto">
        <el-row>
          <el-col v-for="(item, index) in uploadErrorList" :key="index" :span="24" style="margin-bottom: 10px;">{{ index + 1 }}、{{ item }}</el-col>
        </el-row>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button style="padding: 8px 30px;" type="primary" @click="dialogUploadErrorTextVisible = false">关闭</el-button>
        <el-button style="padding: 8px 30px;" type="primary" @click="copyErrorText()">复制</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  getClassifyTree,
  queryPage,
  del,
  dels
} from '@/views/skill/question/api/question'
import { getDictByCode } from '@/views/menu/api'
import Pagination from '@/components/Pagination'
import permission from '@/directive/permission/index.js'
import MyTable from '@/components/Table'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import { getToken } from '@/utils/auth'
import splitPane from 'vue-splitpane'
import { exportSign, importSign } from '@/utils/fileImportOrExportSign'
export default {
  name: 'SkillQuestion',
  components: { Pagination, MyTable, splitPane },
  directives: { permission, elDragDialog },
  data() {
    return {
      treeLoading: false,
      isShow: false,
      showMsg: '单击左侧菜单项进行维护',
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'classifyName'
      },
      treeName: '',
      breadList: [],
      curClassify: {},
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 10
      },
      search: {
        content: ''
      },
      list: [],
      total: 0,
      multipleSelection: [],
      dict: {
        EXAM_STATE: []
      },
      curEditRow: {},
      /* 上传题库相关*/
      loadingUpload: false,
      uploadQuesDialogVisible: false,
      dialogUploadVisible: false,
      uploadaction: '/API-ENTERPRISE-BACKEND/backend/questionBank/questionImport',
      uploadHeaders: { 'ttsxyhcs': getToken() },
      uploadData: {
        classifyid: ''
      },
      uploadErrorList: [],
      dialogUploadErrorTextVisible: false,
      /* 上传题库相关 end*/
      fileType: '' // 下载 or 导入的类型 old旧类型 new闯关类型
    }
  },
  watch: {
    fileType(val) {
      this.uploadaction = val === 'old' ? '/API-ENTERPRISE-BACKEND/backend/questionBank/questionImport' : '/API-ENTERPRISE-BACKEND/backend/questionBank/newQuestionImport'
    }
  },
  created() {
    // this.getList()
    for (const key in this.dict) {
      this.getDict(key)
    }
    this.getTreeData()
  },
  methods: {
    /**
       * 获取分类树
       */
    getTreeData() {
      this.treeLoading = true
      return new Promise((resolve, reject) => {
        getClassifyTree({ classifyType: 'JNZQFL03' }).then(response => {
          this.treeLoading = false
          this.treeData = response.data.data
          this.$nextTick(() => {
            if (this.$route.query.ci) {
              this.$refs.tree.setCurrentKey(this.$route.query.ci)
              this.$nextTick(() => {
                const node = this.$refs.tree.getNode(this.$route.query.ci)
                this.getTreeNode(node)
              })
              this.curClassify = {
                id: this.$route.query.ci
              }
              this.isShow = true
              this.getList()
            }
          })
        }).catch(error => {
          reject(error)
          this.treeLoading = false
        })
      })
    },
    /**
       * 获取当前树节点和其父级节点
       */
    getTreeNode(node) {
      if (node) {
        if (node.label !== undefined) {
          this.breadList.unshift(node.label) // 在数组头部添加元素
          this.getTreeNode(node.parent) // 递归
        }
      }
    },
    /**
       * 清空搜索菜单
       */
    clearSearchTree() {
      this.treeName = ''
      this.$refs.tree.filter('')
    },

    /**
       * 按菜单名称查询
       */
    handleFilterTree() {
      this.$refs.tree.filter(this.treeName)
    },

    filterNode(value, data) {
      if (!value) return true
      return data.classifyName.indexOf(value) !== -1
    },
    handleTreeClick(data, Node) {
      this.breadList = []
      this.getTreeNode(Node)
      this.curClassify = data
      this.isShow = true
      this.getList()
    },
    /**
       * 创建
       */
    handleCreate() {
      this.$router.push({ path: this.$filterPath('questionManage'), name: 'SkillQuestionManage', query: { ci: this.curClassify.id }})
    },
    /**
       * 增加案例题子试题
       */
    handleAddChild(row) {
      this.$router.push({ path: this.$filterPath('questionManage'), name: 'SkillQuestionManage', query: { ci: this.curClassify.id, pai: row.id }})
    },
    /**
       * 修改
       */
    handleUpdate(row) {
      this.$router.push({ path: this.$filterPath('questionManage'), name: 'SkillQuestionManage', query: { ci: this.curClassify.id, i: row.id, pai: row.parentId }})
    },
    handleImport() {
      this.fileType = 'old'
      this.uploadData.classifyid = this.curClassify.id
      this.dialogUploadVisible = true
    },
    handleImportPass() {
      this.fileType = 'new'
      this.uploadData.classifyid = this.curClassify.id
      this.dialogUploadVisible = true
    },
    handleDownload() {
      const link = document.createElement('a')
      link.style.display = 'none'
      const obj = {}
      if (this.fileType === 'new') {
        obj.type = 'new'
      }
      link.href = '/API-ENTERPRISE-BACKEND/backend/questionBank/downloadQuestionTemplate' + exportSign(obj).paramStr
      link.setAttribute('download', '试题模版.xls')
      link.setAttribute('target', '_blank')
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
    handleUploadQues() {
      this.dialogUploadVisible = true
    },
    submitUpload() {
      if (this.$refs['upload'].uploadFiles.length === 0) {
        this.$message.error('请上传文件')
      } else {
        this.$set(this, 'uploadHeaders', importSign(this.uploadHeaders, this.uploadData))
        this.loadingUpload = true
        this.$refs.upload.submit()
      }
    },
    uploadSuccess(data) {
      this.loadingUpload = false
      if (data.code === '200') {
        this.$message({
          message: '试题导入成功',
          type: 'success'
        })
        this.dialogUploadVisible = false
        this.uploadQuesDialogVisible = false
        this.$refs.upload.clearFiles()
        this.getList()
      } else {
        this.$message.error(data.msg || '网络异常')
        this.$refs.upload.clearFiles()
        if (data.data) {
          this.uploadErrorList = data.data
          this.dialogUploadErrorTextVisible = true
        }
      }
    },
    uploadError(err) {
      this.loadingUpload = false
      this.$message.error(err || '网络异常')
    },
    /**
       * 复制错误消息
       */
    copyErrorText() {
      let val = ''
      this.uploadErrorList.forEach(item => {
        val += item + '\n'
      })
      const input = document.createElement('input')
      input.setAttribute('readonly', 'readonly')
      input.setAttribute('value', val)
      document.body.appendChild(input)
      input.select()
      if (document.execCommand('copy')) {
        document.execCommand('copy')
        this.$message({
          title: '成功',
          message: '复制成功！',
          type: 'success',
          duration: 1500
        })
      }
      document.body.removeChild(input)
    },
    /**
       * 批量删除
       */
    handleDeletes() {
      if (this.multipleSelection.length > 0) {
        const arr = this.multipleSelection.map(item => { return item.id }).join(',')
        this.deleteData(arr)
      } else {
        this.$message({
          message: '请选择需要删除的数据！',
          type: 'warning'
        })
      }
    },
    /**
       * 删除
       */
    handleDelete(row) {
      this.del(row.id)
    },
    /**
       * 删除
       * @param ids
       */
    deleteData(ids) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        dels({ ids: ids }).then(res => {
          this.$message.success('删除成功!')
          this.getList()
        })
      }).catch(() => { })
    },
    /**
       * 删除
       * @param ids
       */
    del(ids) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del({ id: ids }).then(res => {
          this.$message.success('删除成功!')
          this.getList()
        })
      }).catch(() => { })
    },
    /**
       * table 列数据过滤
       * @param scope
       * @param item
       * @returns {string}
       */
    filtercolumn(scope, item) {
      if (item === 'opts') {
        return JSON.parse(scope.row['answer']).opts ? JSON.parse(scope.row['answer']).opts.join('、') : ''
      } else if (item === 'answer') {
        return JSON.parse(scope.row['answer']).answers ? JSON.parse(scope.row['answer']).answers.join('、') : ''
      } else if (item === 'questionTypeValue') {
        return scope.row[item] && scope.row['parentId'] ? '案例-' + scope.row[item] : scope.row[item]
      } else {
        return scope.row[item]
      }
    },
    /**
       * 获取字典
       * @param code
       * @returns {Promise<any>}
       */
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code).then(res => {
          this.dict[code] = (res.data.data && res.data.data.length > 0) ? res.data.data[0].list : []
        }).catch(error => {
          reject(error)
        })
      })
    },
    /**
       * 搜索
       */
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    /**
       * 重置
       */
    resettingBtn() {
      this.listQuery.page = 1
      for (const i in this.search) {
        if (this.search['' + i + ''] instanceof Array) {
          this.search['' + i + ''] = []
        } else {
          this.search['' + i + ''] = ''
        }
      }
      this.getList()
    },
    /**
       * 多选
       */
    handleSelectionChange(arr) {
      this.multipleSelection = arr
    },
    /**
       * 获取列表
       */
    getList(obj) {
      const query = {
        stem: this.search.content,
        classifyId: this.curClassify.id,
        page: obj ? obj.page : this.listQuery.page,
        pageSize: obj ? obj.limit : this.listQuery.limit
      }
      this.listLoading = true
      return new Promise((resolve, reject) => {
        queryPage(query).then(res => {
          this.listLoading = false
          this.list = res.data.data.rows || []
          this.total = res.data.data.total || 0
        }).catch(error => {
          reject(error)
          this.listLoading = false
        })
      })
    },
    /**
       * 行样式修改
       * @param row
       * @param rowIndex
       * @returns {{padding: string, height: string, background: string}}
       */
    rowClass({ row, rowIndex }) {
      return {
        padding: '5px 0',
        height: '20px',
        background: 'rgba(247,247,248,1)'
      }
    }
  }
}
</script>
<style lang="scss" type="text/scss">
$dark_gray: #bfced6;
.exam-question {
  padding: 10px 20px 10px 10px;
	overflow: hidden;
	.vue-splitter-container{
		width: 100%;
		overflow: hidden;
	}
  .btn-container-title {
    height: 36px;
    line-height: 36px;
    font-size: 16px;
    font-weight: 600;
    color: rgba(51, 51, 51, 1);
    .btn-container-title-select {
      @include font-color($mainColor);
    }
  }
  .page-info {
    height: calc(100vh - 127px);
    padding: 0px;
		overflow: hidden;
    .page-left {
			height: 100%;
			overflow-y: auto;
      background: #fff;
      margin-right: 10px;
      padding: 10px;
      .search-tree-select {
        margin-bottom: 10px;
      }
      .search-tree-wrap {
        display: flex;
        justify-content: space-between;
        align-items: center;
        .tree-filter {
          padding: 10px 18px;
        }
      }
      .el-tree-node__content {
        margin-top: 10px;
      }
      .el-tree-node__expand-icon.expanded {
        -webkit-transform: rotate(0deg);
        transform: rotate(0deg);
      }
      .el-icon-caret-right:before {
        content: '\E7A0';
        font-size: 14px;
      }
      .el-tree-node__expand-icon.expanded.el-icon-caret-right:before {
        content: '\E7A2';
        font-size: 14px;
      }
    }
    .page-right {
			height: 100%;
			overflow-y: auto;
      padding: 10px;
      position: relative;
      background-color: #fff;
      .ts-con {
        position: absolute;
        top: 10px;
        left: 10px;
        right: 10px;
        bottom: 10px;
        background: white;
        .ts {
          line-height: 30px;
          position: absolute;
          left: 50%;
          top: 50%;
          margin-top: -15px;
          margin-left: -110px;
          width: 210px;
          text-align: center;
          background: white;
          border-radius: 2px;
          box-shadow: 1px 1px 5px #e0dbdb;
          font-size: 14px;
          font-family: Microsoft Yahei In-Bold, Microsoft Yahei,
            Apple LiGothic Medium;
          color: #222222;
        }
      }
    }
  }
  .downFile {
    display: inline-block;
    @include font-color($mainColor);
    font-size: 16px;
    float: right;
    text-decoration: underline;
  }
  .downFile:hover {
    cursor: pointer;
  }
  .el-card {
    margin-bottom: 10px;
    .current-position-name {
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 10px;
    }
  }

  .search {
    background-color: #fff;
    padding: 0 10px;
    .svg-container {
      padding: 0 5px 0 10px;
      color: $dark_gray;
      vertical-align: middle;
      display: inline-block;
      &_login {
        font-size: 20px;
      }
    }
    .search-input {
      width: 60%;
      position: relative;
      &:after {
        content: '';
        position: absolute;
        left: -25px;
        right: 0;
        bottom: 8px;
        height: 1px;
        background: rgba(226, 227, 232, 1);
      }
      input {
        outline: none;
        background: transparent;
        border: none;
        outline: medium;
        padding: 0;
        &:focus {
          outline: none;
          background-color: transparent;
        }
      }
    }
    .search-btn {
      display: inline-block;
      float: right;
      .el-button.is-round {
        padding: 10px 30px;
        margin-right: 34px;
      }
      .search-more {
        font-size: 14px;
        font-weight: 500;
        @include font-color($mainColor);
        cursor: pointer;
        margin-left: 10px;
      }
    }
    &.merge {
      height: 50px;
      line-height: 50px;
    }
    &.separate {
      .search-inner {
        padding-top: 10px;
        .search-inner-item {
          .item-label {
            height: 30px;
            line-height: 30px;
            font-size: 14px;
            color: #a6a6a6;
            font-weight: 400;
          }
          .el-input {
            position: relative;
            &.el-date-editor input {
              padding-left: 30px;
            }
            .el-input__inner {
              border: none;
              padding: 0;
            }
            &:after {
              content: '';
              height: 1px;
              background-color: #e2e3e8;
              position: absolute;
              left: 0;
              right: 0;
              bottom: 0;
            }
          }
        }
      }
      .search-btn {
        text-align: center;
        display: block;
        float: none;
        height: 56px;
        line-height: 56px;
      }
    }
  }

  .grid-content {
    text-align: center;
    .img-con {
      margin-bottom: 20px;
      img {
        width: 150px;
      }
    }
  }
  .el-upload {
    width: 100%;
    .el-upload-dragger {
      width: 100%;
    }
  }
  .btn-container-btns {
    text-align: right;
    margin: 10px 0;
  }
}
</style>
